from fastapi import FastAPI  # 导入FastAPI
import uvicorn
import synonyms
import random

# https://github.com/chatopera/Synonyms

app = FastAPI()  # 创建一个app实例


@app.get("/")  # 编写一个路径操作装饰器
async def root():  # 编写一个路径操作函数
    return {"home page"}


# 取一个近义词
@app.get("/getsynonyms/{word}")
async def root(word: str):
    result = synonyms.nearby(str(word), 4)

    all = result[0]
    print(str(all))
    if len(all) > 0:
        word = str(all[1])
    return word

# 取10个近义词
@app.get("/nearby10/{word}")
async def root(word: str):
    result = synonyms.nearby(str(word))
    all = result[0]
    return all


# 取随机一个近义词
@app.get("/randomsynonyms/{word}")
async def root(word: str):
    result = synonyms.nearby(str(word), 6)

    all = result[0]
    print(str(all))
    if len(all) > 0:
        n = random.sample(range(0, 6), 1)
        word = str(all[int(n[0])])
    return word


# 句子内容近义词替换
@app.get("/sentence/{word}")
async def root(word: str):
    # 先分词
    fenci = synonyms.seg(word)
    words = fenci[0]  # 词性是fenci[1]
    cixing = fenci[1]  # and cixing[index] != 'n'
    strRe = ''
    for index, w in enumerate(words):
        if len(w) > 1 and cixing[index] != 'n' and is_all_chinese(w):
            result = synonyms.nearby(str(w), 10)
            all = result[0]
            if len(all) > 0:
                # n = random.sample(range(0, 3), 1)
                w = str(all[1])
                if not is_all_chinese(w):
                    w = str(all[2])
                    if not is_all_chinese(w):
                        w = str(all[3])
        strRe = strRe + w
    return strRe


# 检验是否全是中文字符
def is_all_chinese(strs):
    for _char in strs:
        if not '\u4e00' <= _char <= '\u9fa5':
            return False
    return True


# 检验是否含有中文字符
def is_contains_chinese(strs):
    for _char in strs:
        if '\u4e00' <= _char <= '\u9fa5':
            return True
    return False


#
if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=False)

#  uvicorn main:app --reload
